package com.example.exception;

import com.alibaba.fastjson.JSON;
import com.example.common.HttpStatus;
import com.example.common.HttpStatusDescriptions;
import com.example.common.ResponseResult;
import com.example.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Autowired
    private HttpStatusDescriptions descriptions;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) {

        int code = HttpStatus.UNAUTHORIZED;
        String json = JSON.toJSONString(ResponseResult.fail(descriptions.getDescription(code), code));
        WebUtils.renderString(response, json);
    }
}